require(['loading'], function(loading) {
	//获取url中的id参数
	var params = getUrlParams();
	var detailId = params.id?params.id:"";
	var parentId, expressArea = '', level = 1;
	var category1='', category2='', category3='';
	var parentId;
	var page = 1;
//	pushVHistory(false);
	history.pushState({},"","");
	window.onpopstate = function(event) {
		if(page == 2){
			$('#delete').show();
			$('.btn-success').click(function(){
				page = 1;
				$('#delete').hide();
				$("#second").animate({"bottom": '-100%'});
			});
			$('.btn-default').click(function(){
				history.pushState({},"","");
				$('#delete').hide();
			});
		}else if(page=1){
			$('#delete').show();
			$('.btn-success').click(function(){
				history.back();
			});
			$('.btn-default').click(function(){
				history.pushState({},"","");
				$('#delete').hide();
			});
		}
	};
	//应用实例化
	var findClass = new Vue({
		el: '#findClass',
		data: {
			detailData: [],
			userData: [],
			provinceData:[],
			oneClassData: [],
			twoClassData:[],
			showLoading: false,
			islowest: false,
			submitable:true,
			detailUrl: wxUrl + '/v3.2/tbuyinginfo/detail.do',
			classUrl: wxUrl + '/v3.2/goodsClass/findSonGoodsClass',
			userDetailUrl: wxUrl + '/v3.2/tuser/detail',
			saveUrl: wxUrl + '/v3.2/tbuyinginfo/save.do',
			areaUrl: wxUrl + '/v3.2/addr/areaList',
			areaItem: {
				params:{
					token: token,
					userToken: userToken,
					parentAreaId: ''
				}
			},
			detailItem: {
				params:{
					token: token,
					userToken: userToken,
					id: detailId
				}
			},
			classItem: {
				params:{
					token: token,
					userToken: userToken,
					parentId: ''
				}
			},
			userDetailItem: {
				params:{
					token: token,
					userToken: userToken
				}
			},
			saveItem: {
				params:{
					token: token,
					userToken: userToken,
					areaId: '',
					categoryId: '',
					latestFreightTime: '',
					title: '',
					buyingNum: '',
					perPrice: '',
					description: '',
					buyerName: '',
					buyerMobile: '',
					buyerAddress: '',
					id: 0
				}
			}
		},
		ready: function() {
			if(detailId != null && detailId != ''){
				this.saveItem.params.id = detailId;
				this.getDetailData();
			}
	    },
		methods: {
			getDetailData: function() {
				//如果是再次编辑则根据id获取求购详情
				this.$http.get(this.detailUrl, this.detailItem)
				.then(function(response) {
					var result = JSON.parse(response.body);
					if(result.data){
						var detailData = result.data.result;
						if(detailData!=null){
							this.$set('detailData', detailData);
							if(detailData.latestFreightTime){
								var newTime = detailData.latestFreightTime.replace(/\-/g, "/"); 
							    var latestFreightTime = new Date(newTime);
							    timePicker.time = latestFreightTime.getTime();
							    $("#target .middle-input").val(latestFreightTime.Format("yyyy-MM-dd"));
						    }
							$('#address1').val(detailData.province.name + " > " + detailData.city.name + " > " + detailData.county.name);
						}
					}
				});
			},
			getClass: function(){ //种类筛选
				if(this.oneClassData.length > 0){
					selectClass(this.oneClassData,this.twoClassData);
				} else {
					var oneClassData = [
					    {'id': '1', 'name': '水果', 'parentId': '0'},
					    {'id': '2', 'name': '蔬菜', 'parentId': '0'},
					    {'id': '3', 'name': '畜牧', 'parentId': '0'},
					    {'id': '4', 'name': '药材', 'parentId': '0'}
					];
					var twoClassData = [
					    {"id": "11", "name": "苹果", "parentId": "1"},
					    {"id": "12", "name": "樱桃", "parentId": "1"},
					    {"id": "13", "name": "柿子", "parentId": "1"},
					    {"id": "21", "name": "白菜", "parentId": "2"},
					    {"id": "22", "name": "菠菜", "parentId": "2"},
					    {"id": "23", "name": "山药", "parentId": "2"},
					    {"id": "31", "name": "羊", "parentId": "3"},
					    {"id": "32", "name": "牛", "parentId": "3"},
					    {"id": "33", "name": "鸡", "parentId": "3"}
					];
					selectClass(oneClassData,twoClassData);
				}
				//模拟ios下拉 商品分类select
				function selectClass(oneData,twoData){
				    var showClassDom = $('#classDt');
				    var oneClassId = $('#oneClassId');
				    var twoClassId = $('#twoClassId');
			        var oneLevelId = showClassDom.attr('data-oneClass-id');
			        var twoLevelId = showClassDom.attr('data-twoClass-id');
			        var classSelect = new IosSelect(2,[oneData, twoData],{
		            	container: '.selectClass',
		                cssUnit:'rem',
		                headerHeight: 0.5,
		                itemHeight: 0.48,
		                itemShowCount: 5,
		                relation: [1, 0, 0, 0],
		                oneLevelId: oneLevelId,
		                twoLevelId: twoLevelId,
		                callback: function (selectOneObj, selectTwoObj) {
		                	if(selectTwoObj.atindex == 3){
		                		oneClassId.val(selectOneObj.id); 
		                    	oneClassId.attr('data-oneClass-name', selectOneObj.name);
		                    	showClassDom.attr('data-oneClass-id', selectOneObj.id);
		                    	showClassDom.html(selectOneObj.name);
		                    	$('#categoryId').val(selectOneObj.id);
		                	}else{
		                		oneClassId.val(selectOneObj.id); 
			                    oneClassId.attr('data-oneClass-name', selectOneObj.name);
			                    twoClassId.val(selectTwoObj.id);
			                    twoClassId.attr('data-twoClass-name', selectTwoObj.name);
			                    showClassDom.attr('data-oneClass-id', selectOneObj.id);
			                    showClassDom.attr('data-twoClass-id', selectTwoObj.id);
			                    showClassDom.html(selectTwoObj.name);
			                    $('#categoryId').val(selectTwoObj.id);
		                	}
		                }
		        	});
			    }
			},
			getDate: function(){ //选择最晚发货日期
				var selectDateDom = $('#selectDate');
    			var showDateDom = $('#showDate');
    			// 初始化时间
    			var now = new Date();
    			var nowYear = now.getFullYear();
			    var nowMonth = now.getMonth() + 1;
			    var nowDate = now.getDate();
			    showDateDom.attr('data-month', nowMonth);
			    showDateDom.attr('data-date', nowDate);
			    //初始化数据
			    function formatMonth() {
			        var arr = [];
			        for (var i = 1; i <= 12; i++) {
			            arr.push({
			                id: i + '',
			                name: i + '月'
			            });
			        }
			        return arr;
			    }
			    function formatDate(count){
			        var arr = [];
			        for (var i = 1; i <= count; i++) {
			            arr.push({
			                id: i + '',
			                name: i + '日'
			            });
			        }
			        return arr;
			    }
			    var monthData = function(callback) {
			        callback(formatMonth());
			    };
			    var dateData = function (month, callback) {
			        if(/^(1|3|5|7|8|10|12)$/.test(month)){
			            callback(formatDate(31));
			        }else if(/^(4|6|9|11)$/.test(month)){
			            callback(formatDate(30));
			        }else if(/^2$/.test(month)){
			            if(nowYear % 4 === 0 && nowYear % 100 !==0 || nowYear % 400 === 0){
			                callback(formatDate(29));
			            }else{
			                callback(formatDate(28));
			            }
			        }else{
			            throw new Error('month is illegal');
			        }
			    };
				//模拟ios下拉 商品分类select
		        var oneLevelId = showDateDom.attr('data-month');
        		var twoLevelId = showDateDom.attr('data-date');
		        var classSelect = new IosSelect(2,[monthData, dateData],{
	            	container: '.selectDate',
	            	title: '最晚发货时间',
	                cssUnit:'rem',
	                headerHeight: 0.5,
	                itemHeight: 0.48,
	                itemShowCount: 5,
	                relation: [1, 0, 0, 0],
	                oneLevelId: oneLevelId,
	                twoLevelId: twoLevelId,
	                callback: function (selectOneObj, selectTwoObj) {
	                	showDateDom.attr('data-month', selectOneObj.id);
                    	showDateDom.attr('data-date', selectTwoObj.id);
                    	showDateDom.html(selectOneObj.name + selectTwoObj.name);
	                }
	        	});
			},
			getProvince: function(){ //地区筛选
				var provinceList = this.provinceData;
				if(provinceList.length > 0){
					selectProvince(provinceList);
				} else {
					this.$http.get(this.areaUrl, this.areaItem)
					.then(function(response){
						var result = JSON.parse(response.body);
						var provinceData = result.data.result;
						this.$set('provinceData', provinceData);
						selectProvince(provinceData);
					});
				}
				//模拟ios下拉 省份select
				function selectProvince(data){
					var showProvinceDom = document.querySelector('#selectProvince');
				    var provinceIdDom = document.querySelector('#provinceId');
				    var provinceId = showProvinceDom.dataset['id'];
			        var provinceName = showProvinceDom.dataset['value'];
			        var provinceSelect = new IosSelect(1,[data],{
		                container: '.selectProvince',
		                cssUnit:'rem',
		                headerHeight: 0.5,
		                itemHeight: 0.48,
		                itemShowCount: 5,
		                oneLevelId: provinceId,
		                callback: function (selectOneObj) {
		                    provinceIdDom.value = selectOneObj.id;
		                    $('#qgChandi').val(selectOneObj.name);
		                    showProvinceDom.dataset['id'] = selectOneObj.id;
		                    showProvinceDom.dataset['value'] = selectOneObj.name;
		                }
		        	});
				}
			},
			editOneValidator: function(){
				var newD = document.getElementById("newD");
				var categoryId = $('#categoryId').val();
				var latestFreightTime = $("#showDate").text();
				var title = $("#qgTitle").val();
				var provinceId = $('#provinceId').val();
				var buyingNum = $("#qgNum").val();
				var perPrice = $("#perPrice").val();
				var description = $("#description").val();
				if(!newD){
					if(categoryId == null || categoryId == ""){
						promptBox("请选择求购产品分类！");
						return;
					}
					if(latestFreightTime == null || latestFreightTime == ""){
						promptBox("请选择最晚发货日期！");
						return;
					}
					if(title == null || title == ""){
						promptBox("请输入标题！");
						return;
					}
					if(provinceId == null || provinceId == ""){
						promptBox("请选择产地要求！");
						return;
					}
					if(buyingNum == null || buyingNum == ""){
						promptBox("请输入求购数量！");
						return;
					}else{
						var re = /^\+?[1-9][0-9]*$/; //正整数-正则表达式
						if(!re.test(buyingNum)) {
							promptBox("数量必须为正整数！");
							return;
						}
					}
					if(perPrice == null || perPrice == ""){
						promptBox("请输入价格！");
						return;
					}else{
						var re = /^(\+)?\d+(\.\d+)?$/; //正数-正则表达式
						if(!re.test(perPrice)) {
							promptBox("价格必须为正数！");
							return;
						}
					}
					if(description == null || description == ""){
						promptBox("请输入描述！");
						return;
					}
					page = 2;
					history.pushState({},"","");
					$("#second").animate({"bottom": 0});
					this.getUserData();
				}
			},
			getUserData: function() {
				//获取用户信息
				this.$http.get(this.userDetailUrl, this.userDetailItem)
				.then(function(response) {
					var result = JSON.parse(response.body);
					var userData_ = result.data.tuser;
					this.$set('userData', userData_);
					if(detailId != null && detailId != ''){
						this.userData.nickName = this.detailData.buyerName;
						this.userData.mobile = this.detailData.buyerMobile;
						this.userData.areaName = this.detailData.buyerAddress;
					}
				});
			},
			saveBuyInfo: function() {
				this.saveItem.params.areaId = $("#provinceId").val(); 
				this.saveItem.params.categoryId = $('#categoryId').val();
				this.saveItem.params.latestFreightTime = $("#showDate").text();
				this.saveItem.params.title = $("#qgTitle").val();
				this.saveItem.params.buyingNum = $("#qgNum").val();
				this.saveItem.params.perPrice = $("#perPrice").val();
				this.saveItem.params.description = $("#description").val();
				this.saveItem.params.buyerName = $("#buyerName").val();
				this.saveItem.params.buyerMobile = $("#buyerMobile").val();
				this.saveItem.params.buyerAddress = $("#buyerAddress").val();
				//提交发布求购 
				if(!this.submitable){
					return;
				}
				this.submitable = false;
				this.$http.get(this.saveUrl, this.saveItem)
				.then(function(response) {
					var result = JSON.parse(response.body);
					if(result.code == 0){
						var success = result.data.flag;
						if(success){
							var topCategoryId = result.data.topCategoryId;
							window.location.href = self_base_path + "/userCenter/releaseSuccess.html?category1=" + topCategoryId;
						}
					}else{
						this.submitable = true;
					}
				},function(response) {
					this.submitable = true;
				});
			},
			checkUserInfo: function(){
				var newD = document.getElementById("newD");
				var categoryId = $('#classInput').val();
				var latstFreightTime = $(".middle-input").val();
				var title = $("#qgTitle").val();
				var buyingNum = $("#qgNum").val();
				var perPrice = $("#perPrice").val();
				var description = $("#description").val();
				var buyerName = $("#buyerName").val();
				var buyerMobile = $("#buyerMobile").val();
				var buyerAddress = $("#buyerAddress").val();
				if(!newD){
					if(buyerName == null || buyerName == ""){
						promptBox("请输入联系人！");
						return;
					}
					if(buyerMobile == null || buyerMobile == ""){
						promptBox("请输入联系人电话！");
						return;
					}else{
						var re = /^[1][34587]\d{9}$/; //手机号码验证正则表达式
						if(!re.test(buyerMobile)) {
							promptBox("请输入正确的手机号码！");
							return;
						}
					}
					if(buyerAddress == null || buyerAddress == ""){
						promptBox("请输入地址！");
						return;
					}
					this.saveBuyInfo();
				}
			},
			checkInteger: function (){
		    	var buyingNum = $("#qgNum").val();
				var re = /^\+?[1-9][0-9]*$/; //正整数-正则表达式
				if(!re.test(buyingNum)) {
					promptBox("数量必须为正整数！");
					return;
				}
		    },
		    checkPrice: function(){
		    	var perPrice = $("#perPrice").val();
				var re = /^(\+)?\d+(\.\d+)?$/; //正数-正则表达式
				if(!re.test(perPrice)) {
					promptBox("价格必须为正数！");
					return;
				}
		    }
		}
	});
});